<template>
    <div class="content">
      <div class="content-head">
        <div class="head-btns">
            <el-button type="primary" size="mini" icon="el-icon-back" @click="backEvent">返回</el-button>
            <el-button v-if="routerQuery.type == 0 || routerQuery.type == 1" type="primary" size="mini" @click="saveBtnEvent(0)">保存</el-button>
            <el-button v-if="routerQuery.type == 0" type="primary" size="mini" @click="saveBtnEvent(1)">保存并生效</el-button>
        </div>
        <el-form :model="formData" :rules="formRules" ref="formRef" inline label-width="80px" :disabled="routerQuery.type == 2">
            <el-form-item label="车间" prop="workShop">
                <el-select v-model="formData.workShop" size="small" placeholder="请选择车间">
                    <el-option label="装配车间" value="装配车间"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="工作中心" prop="workCenter">
                <el-select v-model="formData.workCenter" size="small" placeholder="请选择工作中心">
                    <el-option v-for="item,index in formData.workCenterList" :label="item.workCenterName" :value="item.workCenterId" :key="index"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="产线" prop="lineName">
                <el-select v-model="formData.lineName" @change="lineNameChangeEvent" size="small" placeholder="请选择产线">
                    <el-option v-for="item,index in formData.lineList" :label="item.lineName" :value="item.lineName" :key="index"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="产线昵称" prop="lineAlias">
                <el-input v-model="formData.lineAlias" size="small"></el-input>
            </el-form-item>
        </el-form>
      </div>
      <div class="content-table">
        <div class="table-info">
            <div class="info-tip">产线关联的物料信息</div>
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="addBtnEvent" :disabled="routerQuery.type == 2">添加物料</el-button>
        </div>
        <el-table :data="tableData" v-loading="tableLoading" style="width: 100%;" :max-height="tableMaxHeight" class="content-table-item">
          <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
          <el-table-column prop="materialCode" label="物料编码" width="" align="center">
            <template slot-scope="{ row,$index }">
              <el-input :value="row.materialCode" placeholder="请选择物料编码" size="mini">
                <el-button slot="append" icon="el-icon-search" :disabled="routerQuery.type == 2" @click="selectMaterialEvent($index)"></el-button>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="materialName" label="物料名称" width="" align="center"></el-table-column>
          <el-table-column prop="" label="操作" align="center" fixed="right" width="100">
            <template slot-scope="{row,$index}">
                <el-button type="text" size="mini" style="margin-right: 10px;" @click="deleteBtnEvent(row,$index)" :disabled="routerQuery.type == 2">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 物料选择 -->
      <material-table-dialog :materialTableVisible="materialTableDialogVisible" @change="materialTableDialogChange"></material-table-dialog>
    </div>
</template>
  
<script>
import TableHeadFilter from "@/components/tableHeadFilter/index.vue";
import MaterialTableDialog from "./materialTableDialog.vue";
import T from "@/utils/tools.js";
import { reqWorkCenterLineList,reqLineMaterialConfigById,reqDeleteLineMaterialConfig,reqLineMaterialConfigUpdate } from "@/api/workOrder.js"
export default {
    name:"ProductionLineMaterialSettingEdit",
    components:{
      TableHeadFilter,
      MaterialTableDialog
    },
    data() {
      return {
        routerQuery:{
          type:0,
          id:"",
          lineAlias:""
        },
        formData:{
          workShop:"",
          workCenter:"",
          lineName:"",
          lineAlias:"",
          lineList:[],
          workCenterList:[],
        },
        formRules:{
          workShop:[{required:true,message:'请选择车间',trigger:'change'}],
          workCenter:[{required:true,message:'请选择工作中心',trigger:'change'}],
          lineName:[{required:true,message:'请选择产线',trigger:'change'}],
          lineAlias:[{required:true,message:'请输入产线别名',trigger:'blur'}]
        },
        tableData:[],
        tableLoading:false,
        tableMaxHeight:450,
        materialTableDialogVisible:false,
        tableIndex:0,
      }
    },
    mounted(){
      this.dealRouterQuery();
      this.getWorkCenterLineList();
      this.calculateTableMaxHeight();
      this.getLineMaterialConfigById();
      document.title = "产线关联物料设置编辑";
    },
    methods:{
      getWorkCenterLineList(){
        reqWorkCenterLineList({ page:1,size:500 }).then(response => {
          const list = response.data.data.content;
          const lineList = list.map(val => ({ lineName:val.name,lineCode:val.productionLineCode }));
          const workCenterList = list.map(val => ({ workCenterId:val.workCenterId,workCenterName:val.workCenterName }));
          this.formData.lineList = lineList;
          this.formData.workCenterList = workCenterList;
        })
      },
      selectMaterialEvent(index){
        this.tableIndex = index;
        this.materialTableDialogVisible = true;
      },
      addBtnEvent(){
        const row = {
          randomId:T.getRandomId(),
          materialCode:"",
          materialName:""
        };
        this.tableData.push(row);
      },
      deleteBtnEvent(row,index){
        if(!row.id){
          this.tableData.splice(index,1);
        } else {
          this.$confirm("确定删除当前产线关联的该物料信息吗?", '提示', { confirmButtonText:'确定',cancelButtonText:'取消',type: 'warning'}).then(() => {
            reqDeleteLineMaterialConfig(row.id).then(response => {
              if(response.data.code === 200){
                this.$message({type:"success",message:"删除成功"});
                this.tableData.splice(index,1);
              }
            }).catch(error => {
              this.$message({type:"error",message:"删除失败，请稍后重试"});
              console.log(error);
            })
          })
        }
      },
      getLineMaterialConfigById(){
        const type = this.$route.query.type;
        if(type == 0) return;
        const id = this.$route.query.id;
        const lineAlias = this.$route.query.lineAlias;
        reqLineMaterialConfigById(id).then(response => {
          const {
            id,
            workshopCode,
            workshop,
            workCenterId,
            workCenterName,
            productionBasicUnit,
            productionBasicUnitNumber,
            productionBasicUnitNickName,
            materialCode,
            materialName,
            state 
          } = response.data.data;
          this.formData.workShop = workshop;
          this.formData.workCenter = workCenterId;
          this.formData.lineName = productionBasicUnit;
          this.formData.lineAlias = productionBasicUnitNickName;
          this.tableData = [{id,materialCode,materialName}];
        });
      },
      saveBtnEvent(state = 0){
        let checkResult = false;
        this.$refs.formRef.validate(valid => {
          if(valid) checkResult = true;
        })
        if(!this.tableData.length) checkResult = false;
        this.tableData.forEach(val => {
          if(!val.materialCode || !val.materialName){
            checkResult = false;
          }
        });
        if(!checkResult){
          return this.$notify({ type:"warning", title:'提示',message:'请将信息填写完整'});
        }
        const { workShop,workCenter,lineName,lineAlias } = this.formData;
        const workCenterName = this.formData.workCenterList.find(val => val.workCenterId === workCenter).workCenterName || '';
        const materialList = this.tableData;
        const parameterArray = [];
        for(let i = 0; i < materialList.length; i++){
          const { id = '',randomId = '',materialCode,materialName } = materialList[i];
          const parameter = {
            workshop:workShop,
            workCenterId:workCenter,
            workCenterName,
            productionBasicUnit:lineName,
            productionBasicUnitNickName:lineAlias,
            materialCode,
            materialName,
            state
          }
          if(id) parameter.id = id;
          parameterArray.push(parameter);
        }
        reqLineMaterialConfigUpdate(parameterArray).then(response => {
          if(response.data.code === 200){
            this.$message({type:"success",message:"保存成功"});
            this.backEvent();
          }
        }).catch(error => {
          const errMsg = error.response?.data?.message || error?.message;
          this.$message({type:"error",message:errMsg});
        })
      },
      calculateTableMaxHeight(){
        const dom = document.querySelector(".content-table");
        this.$nextTick(() => {
          this.tableMaxHeight = dom.offsetHeight - 40;
        })
      },
      materialTableDialogChange(parameter){
        const { type,materialInfo } = parameter;
        this.materialTableDialogVisible = false;
        if(type === "close") return;
        const index = this.tableIndex;
        const { materialName,material_code } = materialInfo;
        this.tableData[index].materialName = materialName;
        this.tableData[index].materialCode = material_code;
      },
      lineNameChangeEvent(lineName){
        this.formData.lineAlias = lineName;
      },
      backEvent(){
        this.$router.push({ name:"ProductionLineMaterialSetting" });
      },
      //tableHeadFiler的change事件
      filterChangeEvent(parameter){
        const { state, filterField, selectedValue } = parameter;
        if(state === 'clear'){
          //清空操作
          if(this.formData[filterField] !== ""){
            this.formData[filterField] = "";
            this.getProductionDailyReport();
          }
        }
        if(state === 'confirm'){
          //确定操作
          this.formData[filterField] = selectedValue;
          if(selectedValue !== ""){
            this.getProductionDailyReport();
          }
        }
      },
      dealRouterQuery(){
        const { type } = this.$route.query;
        this.routerQuery.type = type;
        this.routerQuery.id = this.$route.query.id ? this.$route.query.id : "";
        this.routerQuery.lineAlias = this.$route.query.lineAlias ? this.$route.query.lineAlias : "";
      }
    }
}
</script>
  
<style lang='scss' scoped>
  .content{
    width: 100%;
    height: 100%;
    padding: 5px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
  
    .content-head{
      flex:1;
      display: flex;
      flex-direction: column;
      .head-btns{
        margin-bottom: 20px;
      }
    }
    .content-table{
      flex:4;
      .table-info{
        width:100%;
        height: 30px;
        display: flex;
        justify-content: space-between;
      }
    }
  }
</style>